/**  
 *	VisualGroup JavaScript prototype Classes, version 0.1
 *  (c) 2008 Bill Vison <vison_ruan@126.com>
 *
 *
/*--------------------------------------------------------------------------*/
using("Vsg.FlashRemoteHandler");
using("Vsg.CrossDomainAction");
using("Vsg.FlashHttpRequest");

Vsg.FlashRemoteHandler.Submit = function(form, options){
    Vsg.FlashRemoteHandler.Submit.superclass.constructor.call(this, form, options);
};


Ext.extend(Vsg.FlashRemoteHandler.Submit , Ext.form.Action,{
	
	type : 'flashSubmit',
	
	run : function() {
        var o = this.options;
        var method = this.getMethod();
		
		
		if(o.clientValidation === false || this.form.isValid() ) {
			
			// --- get the form values ---
			this.options.params = this.form.getValues();
			
			// --- add request ---
            var $sendObj = this.createCallback(o);

			Ext.apply($sendObj, {
                url:this.getUrl(false),
                method: method,
                headers: o.headers,
                params:this.options.params || {}
            });
			
			
			try {
				Vsg.FlashHttpRequest.request($sendObj);
			} catch (ex) {
				Ext.log(ex);
			}			
			
		} else if (o.clientValidation !== false) {
			this.failureType = Ext.form.Action.CLIENT_INVALID;
			this.form.afterAction(this, false);
		}
	},
	
	success : function(response){
	
        var result = this.processResponse(response);
        if(result === true || result.success){
            this.form.afterAction(this, true);
            return;
        }
        if(result.errors){
            this.form.markInvalid(result.errors);
            this.failureType = Ext.form.Action.SERVER_INVALID;
        }
        this.form.afterAction(this, false);
		
	},
	
	handleResponse : function(response) {
        if(this.form.errorReader){
            var rs = this.form.errorReader.read(response);
            var errors = [];
            if(rs.records){
                for(var i = 0, len = rs.records.length; i < len; i++) {
                    var r = rs.records[i];
                    errors[i] = r.data;
                }
            }
            if(errors.length < 1){
                errors = null;
            }
            return {
                success : rs.success,
                errors : errors
            };
        }
        return Ext.decode(response.responseText);		
	}	
	
});

(function() {
	try {
		Interface.ensureImplements(new Vsg.FlashRemoteHandler.Submit({}), Vsg.FlashRemoteHandler);	
	} catch (e) {
		Ext.log("Class Implement Error :"+"[Vsg.FlashRemoteHandler.Submit] , " + e);
	}
})();
